define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, $window, $timeout, Store_data, Center, GoPage, GoDialog, Auth, $ionicActionSheet, $ionicSideMenuDelegate, GoRegion, GoBrandCat, $ionicLoading, GoCheck, GoMap, GoPicture) {
		$scope.isLoad = false; //可以加载
		$scope.showMap = false;
		$scope.data = new Object();
		$scope.data.store_cat = {
			cats: [{
				list1: [],
				value1: '',
				list2: [],
				value2: '',
				list3: [],
				value3: ''
			}]
		};

		$scope.check_Login = function() {
			return Auth.check_loginInfo();
		}

		//画面加载
		$scope.$on('$ionicView.afterEnter', function(scope, status) {
			//动态设置高度
			GoPage.init_top($scope, 0, 0);

			$scope.init_data();
		}, false);

		// 重新获取用户信息
		$scope.init_data = function(cbComplete) {
			var Infos = Auth.get_loginInfo();

			if(!Infos) {
				GoDialog.toast('未登录');
				return;
			}

			Store_data.get_store({
				'session': Infos.user_id
			}, function(res) {
				if(res.success != true) {
					GoDialog.toast(res.msg);
					return;
				}

				var info = res.result;

				if(!(info.grade && info.grade.length > 0)) {
					GoDialog.toast('数据异常');
					return;
				}

				var s = info.store || {};
				var data = $scope.data;
				data.store = s;

				$scope.isLoad = true;

				initStoreCatSelect();
			}, null, cbComplete)
		}

		// 切换推荐
		$scope.change_regist_source = function(flg) {
			$scope.data.regist_source_flg1 = (flg == 1);
			$scope.data.regist_source_flg2 = (flg == 2);
		}

		function trim(val) {
			return typeof val == 'string' ? val.trim() : val
		}

		function checkRequired(val, name) {
			if(!trim(val)) {
				GoDialog.toast('必须输入' + name);
				return false;
			}

			return true;
		}

		function checkUpdate() {

			var s = $scope.data.store;
			var data = $scope.data;
			for(var k in s) s[k] = trim(s[k]);

			if(!checkRequired(s.company_name, '公司名称')) return
			if(!checkRequired(s.company_no, '统一社会信用代码')) return
			if(!checkRequired(s.company_remark, '经营范围')) return
			if(!checkRequired(s.company_profile, '企业简介')) return

			// 主营分类
			var cats = $scope.data.store.store_cat;
			if(!cats || cats.length == 0) {
				GoDialog.toast('请选择主营分类');
				return
			}

			var hasCats = false;
			for(var i = cats.length - 1; i >= 0; i--) {
				if(!cats[i] || !cats[i].trim()) {
					cats.splice(i, 1);
					continue;
				}

				// 去除重复
				var hasSame = false;
				for(var j = 0; j < i; j++) {
					if(cats[i] == cats[j]) {
						hasSame = true;
						cats.splice(i, 1);
						break;
					}
				}
				if(hasSame) continue;

				hasCats = true;
			}

			if(!hasCats) {
				GoDialog.toast('请选择主营分类');
				return
			}


			if(!(s.store_id && s.store_id == 1)) {
				if(!checkRequired(s.regist_source_code, '途径-开发')) return
				if(!data.regist_source_flg1 && !data.regist_source_flg2 ||
					data.regist_source_flg1 && !trim(s.regist_source_recommend) ||
					data.regist_source_flg2 && (!s.regist_source_other_type || !s.regist_source_other)) {

					GoDialog.toast('需要选填一个【开发】以外的注册途径');
					return;
				}
			}

			if(!s.image_cid || s.image_cid.length == 0) {
				GoDialog.toast('请上传营业执照');
				return;
			}

			if(!s.image_place1 || !s.image_place2 || !s.image_place3 || !s.image_place4) {
				GoDialog.toast('请上传全部库房照片');
				return;
			}

			return true;
		}

		// 保存
		$scope.do_save = function() {
			var Infos = Auth.get_loginInfo();
			if(!Infos) {
				GoDialog.toast('未登录');
				return;
			}

			if(checkUpdate() != true) return;

			var s = $scope.data.store;
			var data = $scope.data;
			if(data.regist_source_flg1) {
				s.regist_source_flg = '1';
				s.regist_source_other_type = '';
				s.regist_source_other = '';
			}
			if(data.regist_source_flg2) {
				s.regist_source_flg = '2';
				s.regist_source_recommend = '';
			}

			var updateParams = {
				'store_id': s.store_id,
				'company_name': s.company_name,
				'company_no': s.company_no,
				'company_remark': s.company_remark,
				'company_profile': s.company_profile,
				'store_cat': s.store_cat,
				'regist_source_code': s.regist_source_code,
				'regist_source_flg': s.regist_source_flg,
				'regist_source_recommend': s.regist_source_recommend,
				'regist_source_other_type': s.regist_source_other_type,
				'regist_source_other': s.regist_source_other,

				'image_cid': s.image_cid,
				'image_cert1': s.image_cert1,
				'image_cert2': s.image_cert2,
				'image_place1': s.image_place1,
				'image_place2': s.image_place2,
				'image_place3': s.image_place3,
				'image_place4': s.image_place4,
				'image_id': s.image_id,
				'image_id2': s.image_id2,
			}

			// 保存
			Store_data.upgrade_warehouse({
				'session': Infos.user_id,
				'updateParams': JSON.stringify(updateParams)
			}, function(res) {
				if(res.success != true) {
					GoDialog.toast(res.msg);
					return;
				}

				GoDialog.toast('申请成功');

				refresh_auth(function() {
					GoPage.go_tabPage('home');
				});

			}, function(e) {
				GoDialog.toast("Connecting error, try again...");
			}, function() {

			})
		}

		// 生成分类值
		function setStoreCat() {
			var sc = $scope.data.store_cat.cats;
			var store_cat = [];

			for(var index = 0; index < sc.length; index++) {
				var cat = sc[index];
				var name = '';
				var value = '';
				for(var i = 1; i <= 3; i++) {
					var v = cat['value' + i];
					if(v) {
						var l = cat['list' + i]
						for(var j = 0; j < l.length; j++) {
							if(v == l[j].id) {
								if(name) name += '/';
								name += l[j].text;
								value = v;
								break;
							}
						}
					} else {
						break;
					}
				}

				if(value) {
					store_cat.push(name + ':' + value);
				} else {
					store_cat.push('');
				}
			}

			$scope.data.store.store_cat = store_cat;
		}

		// 分类三级联动下拉框发生变动
		$scope.change_Catselect = function(index, lvl) {
			if(lvl == 3) {
				setStoreCat();
				return;
			}

			var store_cat = $scope.data.store_cat;
			var cat = store_cat.cats[index];
			var selected_id = cat['value' + lvl];
			GoBrandCat.get_nextlvl({ cat_id: selected_id }, lvl, cat, null, null, function() {
				// done
				setStoreCat()
			})
		}

		$scope.add_StoreCat = function() {
			var store_cat = $scope.data.store_cat;
			var cat = store_cat.cats[0] || {};
			var list1 = cat.list1 || [];
			var newList1 = [];
			for(var i = 0; i < list1.length; i++) {
				newList1.push({
					id: list1[i].id,
					text: list1[i].text,
				})
			}

			store_cat.cats.push({
				list1: newList1,
				value1: '',
				value1_select: {id:0,name:"请选择"},
				list2: [],
				value2: '',
				value2_select: {id:0,name:"请选择"},
				list3: [],
				value3: '',
				value3_select: {id:0,name:"请选择"}
			})

			setStoreCat();
		}
		$scope.doSelectCatRow1 = function(catrow,index){
			//id是值 name是显示
			GoDialog.showSelect("大分类",catrow.list1,catrow.value1_select,function(data){
				catrow.value1 = data.id;
				catrow.value1_select = data;
				$scope.change_Catselect(index,1);
			});
		}
		$scope.doSelectCatRow2 = function(catrow,index){
			//id是值 name是显示
			GoDialog.showSelect("中分类",catrow.list2,catrow.value2_select,function(data){
				catrow.value2 = data.id;
				catrow.value2_select = data;
				$scope.change_Catselect(index,2);
			});
		}
		$scope.doSelectCatRow3 = function(catrow,index){
			//id是值 name是显示
			GoDialog.showSelect("小分类",catrow.list3,catrow.value3_select,function(data){
				catrow.value3 = data.id;
				catrow.value3_select = data;
				$scope.change_Catselect(index,3);
			});
		}
		$scope.regist_source_other_type_items = [{id:"advertisement",name:"广告"},{id:"other",name:"其他"}];
		$scope.regist_source_other_type_select = {id:"",name:"请选择"}
		$scope.doSelectAdvs = function(){
			//id是值 name是显示
			GoDialog.showSelect("小分类",$scope.regist_source_other_type_items,$scope.regist_source_other_type_select,function(data){
				$scope.data.store.regist_source_other_type = data.id;
				$scope.regist_source_other_type_select = data;
			});
		}
		data.store.regist_source_other_type
		// 删除某个分类
		$scope.remove_StoreCat = function(index) {
			var store_cat = $scope.data.store_cat.cats || [];
			if(store_cat.length <= index) return;

			store_cat.splice(index, 1);
			setStoreCat();
		}

		// 分类初始化
		function initStoreCatSelect(cb) {
			try {
				var store_cat = $scope.data.store.store_cat_id || "";
				var inputdata = [store_cat];

				// 初始化地区三级联动
				GoBrandCat.init({ inputdata: inputdata }, function(success, initdata) {
					if(!success && (!initdata || initdata.length == 0)) {
						return;
					}
					$scope.data.store_cat = initdata[0];

				}, function() {

				}, function() {
					setStoreCat();
					cb && cb();
				})
			} catch(ex) {
				cb && cb();
			}

		}


		function refresh_auth(cbComplete) {

			if(Auth.check_loginInfo()) {
				var Infos = Auth.get_loginInfo();
				Center.get_AuthInfo({
					'session': Infos.user_id
				}, function(res) {
					if(res.success == true) {
						var info = res.result;
						for(var k in info) {
							if(info[k] == null || info[k] == undefined) {
								info[k] = '';
							}
						}
					    //更新用户信息
					    info.autologin_token_ios = ionic.Platform.isIOS() ? localStorage.getItem("token") : "";
					    info.autologin_token_android = ionic.Platform.isIOS() ? "" : localStorage.getItem("token");
						Auth.save_loginInfo(info);
					}
				}, null, cbComplete)
			} else {
				cbComplete && cbComplete();
			}
		}

		// 上传图片
		$scope.addStoreImg = function(type) {
			var isArray = false;
			if(type == 'image_licence' || type == 'image_cert1' || type == 'image_cert2') {
				isArray = true;
			}

			GoPicture.upload(function(res) {
				if(!res.success) {
					GoDialog.toast(res.msg);
					return;
				}

				var r = res.result;
				var s = $scope.data.store
				if(!isArray) {
					s[type] = r.image_id;
					s[type + '_path'] = r.image_src;
				} else {
					if (!s[type] || s[type].length == undefined) {
						s[type] = [];
						s[type + '_path'] = [];
					}
					s[type].push(r.image_id);
					s[type + '_path'].push(r.image_src);
				}

				GoDialog.toast(r.image_id);
			});
		}

		$scope.openFileActSheet = function(type, index) {
			var src = $scope.data.store[type + '_path'];

			var isArray = false;
			if(type == 'image_licence' || type == 'image_cert1' || type == 'image_cert2') {
				isArray = true;
			}
			if(isArray) {
				src = src[index];
			}

			var buttons = new Array();
			buttons.push({ text: '删除图片', style: '' });
			buttons.push({ text: '显示大图', style: '' });

			GoDialog.sheet('图片操作', '取消', buttons, function(bindex) {

				if(bindex == 0) {
					GoDialog.confirm('删除图片', '是否要删除该图片？', function() {
						$timeout(function() {
							$scope.sheetActionRemove(type, index, isArray);
						}, 1);
					})
				} else if(bindex == 1) {

				}

				return true;
			});
		}

		$scope.sheetActionRemove = function(type, index, isArray) {
			var s = $scope.data.store

			if(!isArray) {
				s[type] = null;
				s[type + '_path'] = null;
			} else {
				s[type].splice(index, 1);
				s[type + '_path'].splice(index, 1);
			}
		}
	}

	controller.$inject = ['$scope', '$window', '$timeout', 'Store_data', 'Center', 'GoPage', 'GoDialog', 'Auth', '$ionicActionSheet', '$ionicSideMenuDelegate', 'GoRegion', 'GoBrandCat', '$ionicLoading', 'GoCheck', 'GoMap', 'GoPicture'];

	return app.registerController("warehouse_upgradectrl",controller);
});